var content = '',
    timer,
    nextStart = 0,
    hasMore = true,
    readyToLoad = false,
    firstTimeLoad = true,
    autoMarkReadType = [3,4,5,10,17,19],
    lang = $('body').attr('data-lang');

function markRead (id, callback) {
    console.log('markRead: '+ id);
    _url = '/message/ipad/read/';
    $.ajax({
        url: _url,
        type: 'GET',
        dataType: 'json',
        data: {id: id},
        success: function (data) {
            if ( data.success ) {
                if ( callback ) {
                    console.log('callback');
                    callback();
                }
            }
        }
    });
}

function appSchemaEvents (type, notify) {
    console.log('Type: '+ type);
    var _c = $(notify);
    switch (type){
        case 1:
        case 2: // Waypoint 评论页面
            var _tp = _c.attr('data-trip'),
                _wp = _c.attr('data-waypoint');
            btAppSchema.commentWaypoint(_tp, _wp);
        break;
        case 3:
        case 8:
        case 10: // 旅程页面
            var _tp = _c.attr('data-trip');
            btAppSchema.jumpToTrip(_tp);
        break;
        case 11:
            var _where = _c.attr('data-where');
            if ( _where === 'waypoint' ) { // Waypoint 评论页面
                var _tp = _c.attr('data-trip'),
                _wp = _c.attr('data-waypoint');
                btAppSchema.commentWaypoint(_tp, _wp);
            }else if( _where === 'trip' ){ // 旅程评论页面
                var _tp = _c.attr('data-trip');
                btAppSchema.jumpToTripComment(_tp);
            }else if( _where === 'url' ){ // WebView (面包故事 & 精彩内容推荐)
                var _url = _c.attr('data-url');
                btAppSchema.jumpToWeb(_url);
            }
        break;
        case 4:
        case 5:
        case 9: // Waypoint 页面
            var _tp = _c.attr('data-trip'),
                _wp = _c.attr('data-waypoint');
            btAppSchema.jumpToWaypoint(_tp, _wp);
        break;
        case 16:
            var _user = _c.attr('data-user');
            btAppSchema.jumpToMessage(_user);
        break;
        case 18: // 旅程评论页面
            var _tp = _c.attr('data-trip');
            btAppSchema.jumpToTripComment(_tp);
        break;
        case 17:
        case 19:
        case 22:
        case 23:
        case 24: // 用户页面
            var _user = _c.attr('data-user'),
                _name = _c.attr('data-username');
            btAppSchema.jumpToUser( _user, _name);
        break;
        case 20:
        case 21:
            var _type = _c.data('systemtype');
            if ( _type === 1 ) { // 旅程页面
                var _tp = _c.attr('data-trip');
                btAppSchema.jumpToTrip(_tp);
            }else if( _type === 2 ){ // WebView
                var _url = _c.attr('data-url');
                btAppSchema.jumpToWeb(_url);
            }else if( _type === 3 ){ // 用户页面
                var _user = _c.attr('data-user');
                var _name = _c.attr('data-username');
                btAppSchema.jumpToUser( _user, _name);
            }
        break;
        case 25: // WebView
            var _url = _c.attr('data-url');
            btAppSchema.jumpToWeb(_url);
        break;
    }
}

function initPrevAllFn () {
    var e = {
        prevAll: function(s) {
            var $els = $(), $el = this.prev();
            while( $el.length ) {
                if(typeof s === 'undefined' || $el.is(s)) $els = $els.add($el);
                $el = $el.prev();
            }
            return $els;
        }
    };
    $.extend( $.fn, e );
}

function getBottomElement () {
    var _y = $(window).height() - 40,
        _element = $(document.elementFromPoint(300, _y)).parents('li.n');
    console.log(_element);
    $.each(_element.prevAll('li'), function(i, val) {
        var _type = $(val).find('.content').data('type');
        if ( autoMarkReadType.indexOf(_type) != -1 && $(val).attr('data-read') === null ) {
            console.log('marktype: '+_type);
            console.log('belong: '+ _type);
            var _id = $(val).data('id');
            markRead(_id, function () {
                $(val).attr('data-read', 1);
            });
        }
    });
}


$('#list').on('tap', '.content', function(e) {
    if ( !$(e.target).hasClass('btn-relationship') && !$(e.target).parent('a').hasClass('btn-relationship') ) {
        console.log('content');
        e.preventDefault();
        var _type = $(this).data('type');
        var _li = $(this).parents('li');
        var _messageId = _li.data('id');
        _li.hide();
        console.log('Type1: '+ _type);
        breadtrip_notification_count -= 1;
        markRead(_messageId, appSchemaEvents(_type, $(this)));
    }
});

$('#list').on('tap', '.user, .user-info', function(e) {
    e.preventDefault();
    e.stopPropagation();
    var _id = $(this).parents('li').attr('data-userid'),
        _name = $(this).parents('li').attr('data-username');
    btAppSchema.jumpToUser( _id, _name);
});

$('#list').on('tap', '.btn-relationship', function(e) {
    console.log('btn');
    e.preventDefault();
    var _this = $(this);
        _user = _this.parent('.content').attr('data-user'),
        _method = $(this).attr('data-method'),
        _url = '/u/'+ _user +'/friendship/'+ _method +'/',
        _csrf = $('#list').attr('data-csrf');
    console.log($(this));
    console.log('url: '+_url);
    $.ajax({
        url: _url,
        type: 'POST',
        dataType: 'json',
        data: {csrfmiddlewaretoken: _csrf},
        success: function (data) {
            console.log(data);
            if ( data.sucess ) {
                if ( data.relationship === 4 ) {
                    _this.find('b').text($lang['好友']);
                    _this.find('span').removeClass('icon-addfriend').addClass('icon-friend');
                    _this.addClass('btn-pressed');
                    _this.removeClass('btn-relationship');
                }
                if ( data.relationship === 2 ) {
                    _this.find('b').text($lang['已关注']);
                    _this.addClass('btn-pressed');
                    _this.removeClass('btn-relationship');
                }
                btAppSchema.refreshUser(_user,1);
            }
        }
    });
});

function getMore () {
    content = '';
    $.ajax({
        url: '/message/ipad/more/',
        type: 'GET',
        dataType: 'json',
        data: {next_start: nextStart},
        success: function (data) {
            console.log(data);
            $.each(data.notifications, function(i, v) {
                content +='<li class="n" data-id="'+ v.id +'" data-userid="'+ v.from_user.id
                        + '" data-username="'+ v.from_user.name
                        + '"><dl><dt class="user"><p class="pic"><img src="'+ v.from_user.avatar_m
                        + '"></p></dt>';
                console.log(v.type);
                switch(v.type){
                    case 1:
                        content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                + '</b></p><p class="date">'+ v.created_date_short
                                + '</p></div><div class="content type-1" data-type="1" data-trip="'+ v.waypoint.trip_id
                                + '" data-waypoint="'+ v.waypoint.id
                                + '"><p class="title">'+ $lang['评论了你的照片']
                                + '</p><p class="text">“'+ v.comment.content
                                + '”</p><p class="photo"><img src="'+ v.waypoint.photo_w640
                                + '" height="';
                        if ( v.waypoint.photo_info && v.waypoint.photo_info.w < 640 ) {
                            content += (480 * 198 / v.waypoint.photo_info.w);
                        }else{
                            content += '148';
                        }
                        content +='"></p></div></dd>';
                    break;
                    case 2:
                        content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                + '</b></p><p class="date">'+ v.created_date_short
                                + '</p></div><div class="content type-2" data-type="2" data-trip="'+ v.waypoint.trip_id
                                + '" data-waypoint="'+ v.waypoint.id
                                + '"><p class="title">'+ $lang['评论了你的留言']
                                + '</p><p class="text">“'+ v.comment.content
                                + '”</p><p class="message"><span>'+ v.waypoint.text
                                + '</span></p></div></dd>';
                    break;
                    case 3:
                        content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                + '</b></p><p class="date">'+ v.created_date_short
                                + '</p></div><div class="content type-3" data-type="3" data-trip="'+ v.trip.id
                                + '"><p class="title">'+ $lang['收藏了你的旅程']
                                + '</p><p class="text">“'+ v.trip.name
                                + '”</p></div></dd>';
                    break;
                    case 4:
                        content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                + '</b></p><p class="date">'+ v.created_date_short
                                + '</p></div><div class="content type-4" data-type="4" data-trip="'+ v.waypoint.trip_id
                                + '" data-waypoint="'+ v.waypoint.id
                                + '"><p class="title">'+ $lang['喜欢了你的照片']
                                + '</p><p class="photo"><img src="'+ v.waypoint.photo_w640
                                + '" height="';
                        if ( v.waypoint.photo_info && v.waypoint.photo_info.w < 640 ) {
                            content += (480 * 198 / v.waypoint.photo_info.w);
                        }else{
                            content += '148';
                        }
                        content +='"></p></div></dd>';
                    break;
                    case 5:
                        content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                + '</b></p><p class="date">'+ v.created_date_short
                                + '</p></div><div class="content type-5" data-type="5" data-trip="'+ v.waypoint.trip_id
                                + '" data-waypoint="'+ v.waypoint.id
                                + '"><p class="title">'+ $lang['喜欢了你的留言']
                                + '</p><p class="message"><span>'+ v.waypoint.text
                                + '</span></p></div></dd>';
                    break;
                    case 8:
                        content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                + '</b></p><p class="date">'+ v.created_date_short
                                + '</p></div><div class="content type-8" data-type="8" data-trip="'+ v.trip.id
                                + '"><p class="title">'+ $lang['创建了新旅程']
                                + '<a class="link" href="###">'+ v.trip.name
                                + '</a></p>';
                        if ( v.trip.cover_image_w640 !== "" ) {
                            content +='<p class="photo"><img src="'+ v.trip.cover_image_w640
                                    + '" height="';
                            if ( v.waypoint.photo_info && v.waypoint.photo_info.w < 640 ) {
                                content += (480 * 198 / v.waypoint.photo_info.w);
                            }else{
                                content += '148';
                            }
                            content +='"></p>';
                        }
                        content +='</div></dd>';
                    break;
                    case 9:
                        content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                + '</b></p><p class="date">'+ v.created_date_short
                                + '</p></div><div class="content type-9" data-type="9" data-trip="'+ v.waypoint.trip_id
                                + '" data-waypoint="'+ v.waypoint.id
                                + '"><p class="title">'+ $lang['更新了旅程']
                                + '<a class="link" href="###">'+ v.waypoint.trip_name
                                + '</a></p>';
                        if ( v.waypoints && v.waypoints.count > 1 ) {
                            content +='<ol>';
                            $.each(v.waypoints.items, function(j, items) {
                                content +='<li class="photo"><img src="'+ items.photo_s
                                        + '" alt=""></li>';
                            });
                            content +='</ol>';
                        }else{
                            if ( v.waypoint.text !== "" ) {
                                content +='<p class="text">“'+ v.waypoint.text + '”</p>';
                            }
                            if ( v.waypoint.photo_w640  !== "" ) {
                                content += '<p class="photo"><img src="'+ v.waypoint.photo_w640 + '" height="';
                                if ( v.waypoint.photo_info && v.waypoint.photo_info.w < 640 ) {
                                    content += (480 * 198 / v.waypoint.photo_info.w);
                                }else{
                                    content += '148';
                                }
                                content +='"></p>';
                            }
                        }
                        if ( v.waypoints && v.waypoints.count > 6 ) {
                            content +='<p class="btn">'+ v.waypoints.count + $lang['张'] +'</p>';
                        }
                    break;
                    case 10:
                        content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                + '</b></p><p class="date">'+ v.created_date_short
                                + '</p></div><div class="content type-10" data-type="10" data-trip="'+ v.trip.id
                                + '"><p class="title">'+ $lang['结束了旅程']
                                + '<a class="link" href="###">'+ v.trip.name
                                + '</a></p>';
                        if ( v.trip.cover_image_w640 !== undefined ) {
                            content += '<p class="photo"><img src="'+ v.trip.cover_image_w640 + '"></p>';
                        }
                        content +='</div></dd>';
                    break;
                    case 11:
                        if ( v.waypoint != null ) {
                            content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                    + '</b></p><p class="date">'+ v.created_date_short
                                    + '</p></div><div class="content type-11" data-type="11" data-trip="'+ v.waypoint.trip_id
                                    + '" data-waypoint="'+ v.waypoint.id
                                    + '" data-where="waypoint"><p class="title">'+ $lang['回复了你的评论']
                                    + '</p><p class="text">“'+ v.comment.content
                                    + '”</p></div></dd>';
                        }else if( v.trip != null ){
                            content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                    + '</b></p><p class="date">'+ v.created_date_short
                                    + '</p></div><div class="content type-11" data-type="11" data-trip="'+ v.trip.id
                                    + '" data-where="trip"><p class="title">'+ $lang['回复了你的评论']
                                    + '</p><p class="text">“'+ v.comment.content
                                    + '”</p></div></dd>';
                        }else if( v.url != null ){
                            content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                    + '</b></p><p class="date">'+ v.created_date_short
                                    + '</p></div><div class="content type-11" data-type="11" data-url="'+ v.url
                                    + '" data-where="url"><p class="title">'+ $lang['回复了你的评论']
                                    + '</p><p class="text">“'+ v.comment.content
                                    + '”</p></div></dd>';
                        }
                    break;
                    case 16:
                        content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                + '</b></p><p class="date">'+ v.created_date_short
                                + '</p></div><div class="content type-16" data-type="16" data-user="'+ v.from_user.id
                                + '"><p class="title">'+ $lang['向你发送了私信']
                                + '</p><p class="text">“'+ v.private_message.content
                                + '”</p></div></dd>';
                    break;
                    case 17:
                        content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                + '</b></p><p class="date">'+ v.created_date_short
                                + '</p></div><div class="content type-17" data-type="17" data-user="'+ bt_id
                                + '" data-username="'+ bt_name
                                + '" data-destname="'+ v.passport.name
                                + '" data-destid="'+ v.passport.id
                                + '" data-desttype="1"><p class="title">';
                        if ( v.passport.code === 'HK' || v.passport.code === 'MO' ) {
                            content += $lang['恭喜你获得新地区签证！'];
                        }else{
                            content += $lang['恭喜你获得新国家签证！'];
                        }
                        content +='</p><p class="photo"><img src="'+ v.passport.icon
                                + '" height="113"></p></div></dd>';
                    break;
                    case 18:
                        content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                + '</b></p><p class="date">'+ v.created_date_short
                                + '</p></div><div class="content type-18" data-type="18" data-trip="'+ v.trip.id
                                + '"><p class="title">'+ $lang['评论了你的行程']
                                + '</p><p class="text">“'+ v.comment.content
                                + '”</p></div></dd>';
                    break;
                    case 19:
                        content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                + '</b></p><p class="date">'+ v.created_date_short
                                + '</p></div><div class="content type-19" data-type="19" data-user="'+ v.ext_user.id
                                + '" data-username="'+ v.ext_user.name
                                + '"><p class="title"> '+ $lang['你的好友'] + v.ext_user.name + $lang['获得新签证！']
                                + ' </p><p class="photo"><img src="'+ v.passport.icon
                                + '" height="113"></p></div></dd>';
                    break;
                    case 20:
                    case 21:
                        content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                + '</b></p><p class="date">'+ v.created_date_short
                                + '</p></div>';
                        if ( v.system_message.type === 1 ) {
                            content +='<div class="content type-'+v.type+'" data-type="'+v.type+'" data-systemtype="'+ v.system_message.type
                                    + '" data-trip="'+ v.system_message.trip.id
                                    + '"><p class="title">'+ v.system_message.content
                                    + '</p><p class="photo">';
                            if ( v.system_message.cover !== undefined ) {
                                console.log('type: '+ typeof(v.system_message.cover));
                                content +='<img src="'+ v.system_message.cover
                                        + '" alt=""></p></div>';
                            }else{
                                content +='<img src="'+ v.system_message.trip.cover_image_w640
                                        + '" alt=""></p></div>';
                            }
                        }else if( v.system_message.type === 2 ){
                            content +='<div class="content type-'+v.type+'" data-type="'+v.type+'" data-systemtype="'+ v.system_message.type
                                    + '" data-url="'+ v.system_message.url
                                    + '"><p class="title">'+ v.system_message.content
                                    + '</p><p class="photo"><img src="'+ v.system_message.cover
                                    + '" alt=""></p></div>';
                        }else if( v.system_message.type === 3 ){
                            content +='<div class="content type-'+v.type+'" data-type="'+v.type+'" data-systemtype="'+ v.system_message.type
                                    + '" data-user="'+ v.system_message.user.id
                                    + '" data-username="'+ v.system_message.user.name
                                    + '"><p class="title">'+ v.system_message.content
                                    + '</p><p class="photo">';
                            if ( v.system_message.cover !== undefined ) {
                                console.log('type: '+ typeof(v.system_message.cover));
                                content +='<img src="'+ v.system_message.cover
                                        + '" alt=""></p></div>';
                            }else{
                                content +='<img src="'+ v.system_message.user.avatar_l
                                        + '" alt=""></p></div>';
                            }
                        }
                    break;
                    case 22:
                        content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                + '</b></p><p class="date">'+ v.created_date_short
                                + '</p></div><div class="content type-22" data-type="22" data-user="'+ v.from_user.id
                                + '" data-username="'+ v.from_user.name
                                + '">';
                        if ( v.from_user.relationship === 1 ){
                            content +='<a data-method="follow" class="btn btn-relationship" href="###"><span class="icons icon-follow"></span><b>'+ $lang['关注']
                                    + '</b></a>';
                        }else if( v.from_user.relationship === 2 ){
                            content +='<a data-method="mark_friend" class="btn btn-relationship" href="###"><span class="icons icon-addfriend"></span><b>'+ $lang['加好友']
                                    + '</b></a>';
                        }
                        content +='<p class="title">'+ $lang['关注了你']
                                + '</p></div></dd>';
                    break;
                    case 23:
                        content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                + '</b></p><p class="date">'+ v.created_date_short
                                + '</p></div><div class="content type-22" data-type="22" data-user="'+ v.from_user.id
                                + '" data-username="'+ v.from_user.name
                                + '">';
                        if ( v.from_user.relationship === 1 ){
                            content +='<a data-method="follow" class="btn btn-relationship" href="###"><span class="icons icon-follow"></span><b>'+ $lang['关注']
                                    + '</b></a>';
                        }else if( v.from_user.relationship === 2 ){
                            content +='<a data-method="mark_friend" class="btn btn-relationship" href="###"><span class="icons icon-addfriend"></span><b>'+ $lang['加好友']
                                    + '</b></a>';
                        }
                        content +='<p class="title">'+ $lang['加你为好友'] +'</p></div></dd>';
                    break;
                    case 24:
                        content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                + '</b></p><p class="date">'+ v.created_date_short
                                + '</p></div><div class="content type-24" data-type="24" data-user="'+ v.from_user.id
                                + '" data-username="'+ v.from_user.name
                                + '"><a data-method="follow" class="btn btn-relationship" href="###"><span class="icons icon-follow"></span><b>'+ $lang['关注']
                                + '</b></a><p class="title">'+ $lang['你好友加入了面包旅行']
                                + '</p></div></dd>';
                    break;
                    case 25:
                        content +='<dd><div class="user-info"><p><b>'+ v.from_user.name
                                + '</b></p><p class="date">'+ v.created_date_short
                                + '</p></div><div class="content type-25" data-type="25" data-url="'+ v.url
                                + '"><p class="title">'+ $lang[v.title? v.title: '评论了你的面包故事']
                                + '</p><p class="text">“'+ v.comment.content
                                + '”</p></div></dd>';
                    break;

                };
                content += '</dl></li>';
            });
            readyToLoad = true;
            hasMore = data.more;
            nextStart = data.next_start;
            if ( firstTimeLoad ) {
                loadMore();
                firstTimeLoad = false;
                getBottomElement();
            }
            if ( !hasMore ) { $('#more').hide(); }
        }
    });
}

function loadMore () {
    if ( readyToLoad ) {
        var _reachBottom = document.body.scrollTop + window.innerHeight >= $(document).height() - 200;
        if ( _reachBottom ) {
            console.log("reach");
            $(content).appendTo("#list");
            $('#more span').text($lang['正在加载更多']);
            readyToLoad = false;
            if ( hasMore ) {
                getMore();
            }
        }
    }
}

// $(document).ready(function() {
    console.log('ready');
    initPrevAllFn();
    getMore();
// });

$(window).on('scroll', function () {
    if ( timer ) clearTimeout(timer);
    timer = setTimeout(function(){
        loadMore();
        getBottomElement();
    }, 300);
});
